package com.example.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.entity.Users;
import com.example.service.UsersService;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import org.slf4j.Logger;

/**
 * JWT工具
 * */
@Component
public class JwtTokenUtils {
    private static UsersService staticUsersService;
    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);

    @Resource
    private UsersService usersService;

    @PostConstruct
    public void setUserService(){
        staticUsersService = usersService;
    }

    /**
     * 使用JWT进行鉴权
     * 用户在登录成功后，服务端可以生成一个包含用户信息的JWT，并将其返回给客户端
     *客户端每次请求时都会携这个JWT
     * 服务端通过验证JWT的签名来确认用户的身份
     * */
    //生成token,userId作为载荷，password作为签名
    public static String genToken(String userId , String password){
        return JWT.create().withAudience(userId) //将userId保存到token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //2小时后token过期
                .sign(Algorithm.HMAC256(password)); //以password作为token的密钥
    }

    //获取当前登录的用户信息(日志管理)
    public static Users getCurrentUser(){
        String token = null;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("token");
            if(StrUtil.isBlank(token)){
                token = request.getParameter("token");
            }
            if(StrUtil.isBlank(token)){
                log.error("获取当前登录的token失败，token:{}",token);
                return null;
            }
            //解析token,获取用户的id
            String userId = JWT.decode(token).getAudience().get(0);
            return staticUsersService.findById(Integer.valueOf(userId));
        }catch (Exception e){
            log.error("获取当前登录的用户信息失败，token={}",token, e);
            return null;
        }
    }
}
